//
//  BaseTabBarController.swift
//  QingLiuSwift
//
//  Created by 徐先生 on 2023/3/29.
//

import UIKit
import Localize_Swift
import Reusable

class BaseTabBarController: UITabBarController {
    /// 首页
    var home: BaseNavigationController!
    /// 工作台
    var work: BaseNavigationController!
    /// 消息
    var message: BaseNavigationController!
    /// 我的
    var mine: BaseNavigationController!
    
    // 强制更新
    private lazy var forcedUpdatingView = {
        let view = ForcedUpdatingView.loadFromNib()
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpTabBar()
        delegate = self
        // 设置默认选中位置
        selectedIndex = 2
        
        if #available(iOS 18.0, *) {
            // 使用Xcode16 & iOS 18 运行项目后，UITabbarController切换到时候会有一个微小的缩放动画。
            // https://www.jianshu.com/p/57a4ae48c6df
            delegate = self
        }
        
        // 监听语言的变化
        NotificationCenter.default.addObserver(self, selector: #selector(updateLanguageAction), name: NSNotification.Name(LCLLanguageChangeNotification), object: nil)
        // app启动或者app从后台进入前台都会调用这个方法
        NotificationCenter.default.addObserver(self, selector: #selector(applicationBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
         // xLog("BaseTabBarController - viewDidAppear")
        initForcedUpdating()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // xLog("BaseTabBarController - viewDidAppear")
    }
    
    
    // MARK: - 控制器的信息
    func setUpTabBar() {
        
        home = configurationTabbarItem(
            viewController: HomeMainController(),
            // viewController: PostListViewController(),
            image: "ic_tabbar_home_nor",
            selectImage: "ic_tabbar_home_sel",
            title: "首页".localized(),
            tag: 0
        )
        work = configurationTabbarItem(
            viewController: WorkMainController(),
            image: "ic_tabbar_word_nor",
            selectImage: "ic_tabbar_word_sel",
            title: "工作台".localized(),
            tag: 1
        )
        
        message = configurationTabbarItem(
            viewController: MessageMainController(),
            image: "ic_tabbar_message_nor",
            selectImage: "ic_tabbar_message_sel",
            title: "消息".localized(),
            tag: 2
        )
        mine = configurationTabbarItem(
            viewController: MineMainController(),
            image: "ic_tabbar_mine_nor",
            selectImage: "ic_tabbar_mine_sel",
            title: "我的".localized(),
            tag: 3
        )
        
        // 设置 tabBar & tabBarItem
        setTabBarItemAttributes()
    }
    
    /// 这种方式比较灵活
    func setTabBarItemAttributes(fontName: String = "Courier",
                                 fontSize: CGFloat = 14,
                                 normalColor: UIColor = UIColor(hex: "333333"),
                                 selectedColor: UIColor = UIColor(hex: "FF0000"),
                                 bgColor: UIColor = .white) {
        // tabBarItem 文字大小
        var attributes: [NSAttributedString.Key: Any] = [.font: UIFont(name: fontName, size: fontSize)!]
        
        // tabBarItem 文字默认颜色
        attributes[.foregroundColor] = normalColor
        UITabBarItem.appearance().setTitleTextAttributes(attributes, for: .normal)
        // tabBarItem 文字选中颜色
        attributes[.foregroundColor] = selectedColor
        UITabBarItem.appearance().setTitleTextAttributes(attributes, for: .selected)
        tabBar.unselectedItemTintColor = normalColor
        
        //防止点击后 图片没有改变
        UITabBarItem.appearance().image?.withRenderingMode(.alwaysOriginal)
        UITabBarItem.appearance().selectedImage?.withRenderingMode(.alwaysOriginal)
        
        // tabBar 文字、图片 统一选中高亮色
        //tabBar.tintColor = selectedColor
        
        // tabBar 背景色
        tabBar.backgroundColor = bgColor
    }
    
    
    // MARK: - 配置 TabbarItem
    func configurationTabbarItem(viewController: UIViewController, image: String, selectImage: String, title: String, tag: Int) -> BaseNavigationController {
        // alwaysOriginal 始终绘制图片原始状态，不使用Tint Color。
        viewController.tabBarItem.image = UIImage(named: image as String)?.withRenderingMode(.alwaysOriginal)
        viewController.tabBarItem.selectedImage = UIImage(named: selectImage as String)?.withRenderingMode(.alwaysOriginal)
        viewController.tabBarItem.title = title as String
        viewController.tabBarItem.tag = tag
        viewController.tabBarItem.setTitleTextAttributes([
            NSAttributedString.Key.font : UIFont.systemFont(ofSize: 12, weight: .medium),
            NSAttributedString.Key.foregroundColor: UIColor(hex: "#8C8C8C")
        ], for: .normal)
        viewController.tabBarItem.setTitleTextAttributes([
            NSAttributedString.Key.font : UIFont.systemFont(ofSize: 12, weight: .medium),
            NSAttributedString.Key.foregroundColor: UIColor(hex: "#278AFF")
        ], for: .selected)
        
        let nav = BaseNavigationController(rootViewController: viewController)
        addChild(nav)
        return nav
    }
    
    // 更新语言
    @objc func updateLanguageAction() {
        home.tabBarItem.title = "首页".localized()
        work.tabBarItem.title = "工作台".localized()
        message.tabBarItem.title = "消息".localized()
        mine.tabBarItem.title = "我的".localized()
    }
    
    // app启动或者app从后台进入前台都会调用这个方法
    @objc func applicationBecomeActive() { }
    
    
    /// 更新 TabBar 的 badgeValue
    /// - Parameters:
    ///   - index: 位置
    ///   - count: 数量
    static func updateTabBarBadgeValue(index: Int, count: Int) {
        let rootViewController = xKeyWindow.rootViewController!
        if rootViewController.isKind(of: BaseTabBarController.self) {
            let tabBarController = rootViewController as! BaseTabBarController
            tabBarController.tabBar.items?[index].badgeValue = count > 0 ? "\(count)": nil
        }
    }
}

extension BaseTabBarController {
    // 强制更新
    func initForcedUpdating() {
        
        let target = LoginAPI.systemForcedUpdating
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataDictionary = res.dataDictionary
                
                if let version = dataDictionary["version"] as? String {
                    // 需要强更
                   xLog("强更版本: \(version)")
                    
                    if Bundle.sg.appVersion.sg.compareVesion(to: version) == -1 {
                        forcedUpdatingView.isHidden = false
                        let content = dataDictionary["title"] as! String
                        let contentRu = dataDictionary["title_ru"] as! String
                        
                        forcedUpdatingView.versionLabel.text = version
                        forcedUpdatingView.updateContent = LanguageManager.isLanguageZH ? content: contentRu
                        view.addSubview(forcedUpdatingView)
                        view.bringSubviewToFront(forcedUpdatingView)
                    }
                }
                
            case .failure: break
            }
        }
    }
}


// MARK: - UITabBarControllerDelegate
extension BaseTabBarController: UITabBarControllerDelegate {
    
    // MARK: - UITabBarControllerDelegate
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        return true
    }
    
    func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self
    }
}

extension BaseTabBarController: UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: (any UIViewControllerContextTransitioning)?) -> TimeInterval {
        .zero
    }
    
    func animateTransition(using transitionContext: any UIViewControllerContextTransitioning) {
        guard let view = transitionContext.view(forKey: .to) else { return }
        transitionContext.containerView.addSubview(view)
        transitionContext.completeTransition(true)
    }
}
